package com.starwish.starwishblog.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.starwish.starwishblog.entity.Role;
import com.starwish.starwishblog.mapper.RoleMapper;
import com.starwish.starwishblog.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleService {
    @Autowired
    RoleMapper roleMapper;

    public PageInfo<Role> queryByCons(Integer now, Integer size, String name){
        PageHelper.startPage(now,size);
        List<Role> list = roleMapper.selectRoleByName(name);
        return new PageInfo<>(list);
    }

    public int add(Role role){
        return roleMapper.insert(role);
    }

    public int modify(Role role){
        return roleMapper.updateByPrimaryKey(role);
    }
    @Transactional
    public int removeByKey(Integer id){
        roleMapper.deleteManagerRoleByRoleId(id);
        roleMapper.deleteRolePermissionByRoleId(id);
        int i = roleMapper.deleteByPrimaryKey(id.longValue());
        return i;
    }

    public Role queryRoleById(Integer id){
        return roleMapper.selectByPrimaryKey(id.longValue());
    }

    public PageInfo<RoleVo> queryRoleVoByCons(Integer now, Integer size, String name) {
        PageHelper.startPage(now,size);
        List<RoleVo> list = roleMapper.selectRoleVoByName(name);
        for (RoleVo roleVo : list) {
            System.out.println(roleVo);
        }
        return new PageInfo<>(list);
    }

    public List<Integer> queryPerIdsoByRoleKey(Integer id) {
        return roleMapper.selectPerIdsByRoleKey(id);
    }


    @Transactional
    public void rolePer(RoleVo roleVo) {
        //先删除 当前角色的所有权限
        roleMapper.deleteRolePermissionByRoleId(roleVo.getId());
        //在保存新的权限
        roleMapper.insertBatchRoleAndPer(roleVo.getId(),roleVo.getCheckedIds());
    }

    public void authorityToRole(RoleVo roleVo) {
        //先删除 当前角色的所有权限
        roleMapper.deleteRolePermissionByRoleId(roleVo.getId());
        //在保存新的权限
        roleMapper.insertBatchRoleAndPer(roleVo.getId(),roleVo.getCheckedIds());
    }

    public List<Role> queryAllRoles() {
        return roleMapper.selectAll();
    }
}
